<template>
  <div class="app-container">

    <el-row :gutter="10">
      <el-col :span="18">
        <el-descriptions :title="'线索：' + this.clueId">
          <el-descriptions-item label="创建时间">{{clue.createTime}}</el-descriptions-item>
          <el-descriptions-item label="归属时间">{{assignRecord.createTime}}</el-descriptions-item>
          <el-descriptions-item label="手机号">{{clue.phone}}</el-descriptions-item>
          <el-descriptions-item label="渠道来源">
            <el-tag size="small">{{selectDictLabel(dict.type.clues_item, clue.channel)}}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="线索分配">{{assignRecord.createBy}}</el-descriptions-item>
          <el-descriptions-item label="线索归属">{{assignRecord.userName}}</el-descriptions-item>
          <el-descriptions-item label="活动信息">{{clue.activityId}}</el-descriptions-item>
        </el-descriptions>
        <div style="display: flex; direction: rtl;">
          <el-button style="margin-left: 5px;" v-if="!disabled && clue.status != 4 && clue.status != 5" type="success" @click="handleTransform">转商机</el-button>
          <el-button v-if="!disabled && clue.falseCount < 3 && clue.status != 5" type="danger" @click="handleFakeClue">伪线索</el-button>
        </div>
        <el-divider/>

        <el-form :disabled="disabled" ref="form" size="mini" :model="form" :rules="rules" label-width="100px">
          <el-row>
            <el-col :span="8">
              <el-form-item label="客户姓名" prop="name">
                <el-input v-model="form.name" placeholder="请输入客户姓名" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="性别">
                <el-radio-group v-model="form.sex">
                  <el-radio
                    v-for="dict in dict.type.sys_user_sex"
                    :key="dict.value"
                    :label="dict.value"
                  >{{dict.label}}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="年龄" prop="phone">
                <el-input v-model="form.age" placeholder="请输入年龄" type="number" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="微信号" prop="weixin">
                <el-input v-model="form.weixin" placeholder="请输入微信号" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="qq号" prop="qq">
                <el-input v-model="form.qq" placeholder="请输入qq号" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="意向等级" prop="level">
                <el-select v-model="form.level" placeholder="意向等级">
                  <el-option
                    v-for="dict in dict.type.clues_level"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="意向学科">
                <el-select v-model="form.subject" placeholder="意向学科">
                  <el-option
                    v-for="dict in dict.type.course_subject"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="跟进记录" prop="record">
                <el-input type="textarea" v-model="form.record" placeholder="请输入跟进记录" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="下次跟进时间" prop="nextTime">
                <el-date-picker
                  v-model="form.nextTime"
                  type="datetime"
                  format="yyyy-MM-dd HH:mm"
                  placeholder="选择日期时间">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item v-if="!disabled">
            <el-button v-if="clue.status == 0 || clue.status == 1 || clue.status == 2" type="primary" @click="submitForm">确 定</el-button>
            <el-button type="primary" @click="cancel">取消</el-button>
          </el-form-item>
        </el-form>
        <el-button v-if="disabled" type="primary" @click="cancel">取消</el-button>
      </el-col>
      <el-col :span="6">
        <track-list :key="componentKeys.trackListKey" :id="clueId" :search="'线索跟进记录'"></track-list>
      </el-col>
    </el-row>
    <!-- 伪线索上报   -->
    <false-clue-dialog ref="falseClueDialog"
                       :clueId="clueId"
                       @success="refreshTrackList"
    ></false-clue-dialog>
  </div>
</template>

<script>
import { listClueTrack, addClueTrack, fakeClue, transform } from "@/api/crm/clueTrack";
import { getClue } from "@/api/crm/clue";
import { listAssignRecord } from "@/api/crm/assignRecord";
import TrackList from '@/views/crm/business/operation/track-list'
import FalseClueDialog from '@/views/crm/clue/operation/false-clue'

export default {
  name: "ClueTrack",
  components: {TrackList, FalseClueDialog},
  dicts: ['sys_normal_disable', 'reasons_for_reporting', 'clues_item', 'sys_user_sex', 'clues_level', 'course_subject'],
  props: {
    clueId: [String, Number],
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      componentKeys: {
        trackListKey: 0,
      },
      clue: {},
      assignRecord: {},
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },

    };
  },
  created() {
      console.log('track created...')
     this.refreshData();
  },
  watch: {
    clueId: {
      handler(newValue, oldValue) {
          this.refreshData()
          this.refreshTrackList()
      },
      immediate: true
    }
  },
  methods: {
    refreshData() {
      this.getClue()
      this.getAssignRecord()
    },
    getClue() {
      getClue(this.clueId).then(resp=>{
        this.clue = resp.data
        this.form = this.clue
      })
    },
    getAssignRecord() {
      // 简单调用自动生成的分页代码，取最大id的对象当作最近的分配记录
      listAssignRecord({assignId: this.clueId, type: 0, pageNum: 1, pageSize: 5, orderByColumn: 'id', isAsc: 'desc'}).then(resp => {
        if(resp.rows && resp.rows.length > 0) {
          this.assignRecord = resp.rows.reduce((a1, a2) => { return a1.id > a2.id ? a1 : a2});
        }
      })
    },
    // 表单重置
    reset() {
      this.form = {
        clueId: null,
        name: null,
        phone: null,
        channel: null,
        activityId: null,
        sex: "0",
        age: null,
        weixin: null,
        qq: null,
        level: null,
        subject: null,
        status: "0",
        createTime: null,
        createBy: null,
        falseCount: null,
        nextTime: null,
        updateTime: null,
        transfer: null,
        endTime: null
      };
      this.resetForm("form");
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          addClueTrack(this.form).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.refreshData();
            this.componentKeys.trackListKey += 1;
            this.$emit('success')
          });
        }
      });
    },
    cancel() {
      this.$emit('cancel');
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除线索编号为"' + ids + '"的数据项？').then(function() {
        return delClue(ids);
      }).then(() => {
        this.getClue();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('crm/clue/export', {
        ...this.queryParams
      }, `clue_${new Date().getTime()}.xlsx`)
    },

    handleFakeClue() {
      this.$refs.falseClueDialog.open = true;
      this.$refs.falseClueDialog.resetForm();
    },

    handleTransform() {
      this.$modal.confirm(`确定转换成线索${this.clueId}为商机吗？`).then(() => {
        transform({record: '转商机', clueId: this.clueId, userName: this.$store.getters.name}).then(resp => {
          this.$modal.msgSuccess('操作成功')
          this.$emit('success', {drawer: false})
        })
      });
    },
    refreshTrackList() {
      this.componentKeys.trackListKey += 1;
      this.$emit('success')
    }
  }
};
</script>
